<template>
  <div class="sample-info-query">
    <!-- 头部容器 -->
    <div class="header-container">
      <!-- 标题和搜索区域 -->
      <div class="title-section">
        <h2 class="page-title">采样信息查询</h2>
        <div class="search-section">
          <!-- 第一行 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="采样日期" class="form-item">
                <el-date-picker
                    v-model="searchForm.sampleDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                    class="full-width"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采样编号" class="form-item">
                <el-input v-model="searchForm.sampleNumber" placeholder="请输入采样编号" clearable class="full-width"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品名称" class="form-item">
                <el-input v-model="searchForm.sampleName" placeholder="请输入样品名称" clearable class="full-width"/>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="检测状态" class="form-item">
                <el-select
                    v-model="searchForm.sampleStatus"
                    placeholder="请选择检测状态"
                    clearable
                    class="full-width"
                >
                  <el-option
                      v-for="item in sampleStatusStrs"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="被检单位" class="form-item">
                <el-select
                    v-model="searchForm.inspectionUnit"
                    placeholder="请选择被检单位"
                    clearable
                    class="full-width"
                >
                  <el-option
                      v-for="item in inspectionUnitOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="search-buttons">
              <el-button type="primary" @click="search" :loading="loading.search">
                <el-icon>
                  <Search/>
                </el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch" :loading="loading.reset">
                <el-icon>
                  <Refresh/>
                </el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 统计信息区域 -->
    <div class="stats-container">
      <!-- 总体统计 -->
      <div class="stats-section">
        <h3 class="stats-title">总体统计</h3>
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-icon total-icon">
              <el-icon>
                <Collection/>
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">总采样数量</div>
              <div class="stat-value">{{ totalTasks }}</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon tested-icon">
              <el-icon>
                <Checked/>
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">已检测数量</div>
              <div class="stat-value">{{ testedTasks }}</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon untested-icon">
              <el-icon>
                <Clock/>
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">未检测数量</div>
              <div class="stat-value">{{ untestedTasks }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 今日统计 -->
      <div class="stats-section">
        <h3 class="stats-title">今日统计</h3>
        <div class="stats-cards">
          <div class="stat-card">
            <div class="stat-icon today-icon">
              <el-icon>
                <Calendar/>
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">今日采样数量</div>
              <div class="stat-value">{{ todayTasks }}</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon today-tested-icon">
              <el-icon>
                <CircleCheck/>
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">今日已检数量</div>
              <div class="stat-value">{{ todayTestedTasks }}</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon today-untested-icon">
              <el-icon>
                <Timer/>
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">今日未检数量</div>
              <div class="stat-value">{{ todayUntestedTasks }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-wrapper">
        <el-table
            v-loading="loading.table"
            :data="currentTableData"
            border
            stripe
            highlight-current-row
            style="width: 100%"
            height="100%"
            @row-click="handleRowClick"
        >
          <el-table-column align="center" prop="sampleNumber" label="采样编号"/>
          <el-table-column align="center" prop="sampleCategory" label="样品大类"/>
          <el-table-column align="center" prop="sampleName" label="样品名称"/>
          <el-table-column align="center" prop="sampleDate" label="采样日期"/>
          <el-table-column align="center" prop="sampleSource" label="样品来源"/>
          <el-table-column align="center" prop="inspectionUnit" label="被检单位"/>
          <el-table-column align="center" prop="sampleStaff" label="检测单位"/>
          <el-table-column align="center" prop="sampleStatus" label="检测状态">
            <template #default="{ row }">
              <el-tag style="font-weight: bold;" :type="row.sampleStatus   === '已检' ? 'success' : 'warning'">
                {{ row.sampleStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click.stop="showSampling(row)">
                  <el-icon>
                    <Download/>
                  </el-icon>
                  采样图片
                </el-button>
                <el-button type="primary" size="small" @click.stop="showCertificatePicDialog(row)">
                  <el-icon>
                    <Download/>
                  </el-icon>
                  签名图片
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100, total]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 单图弹窗 -->
    <SinglePicDialog
        v-model="singlePicDialog.visible"
        :title="singlePicDialog.title"
        :image-data="singlePicDialog.imageData"
        :loading="singlePicDialog.loading"
    />

    <!-- 双图弹窗 -->
    <CertificatePicDialog
        v-model="certificatePicDialog.visible"
        :title="certificatePicDialog.title"
        :sampler-image-data="certificatePicDialog.samplerImageData"
        :inspection-image-data="certificatePicDialog.inspectionImageData"
        :loading="certificatePicDialog.loading"
    />
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import {
  Search,
  Refresh,
  Calendar,
  Clock,
  Download,
  Collection,
  Checked,
  CircleCheck,
  Timer
} from '@element-plus/icons-vue';
import SinglePicDialog from "~/layout/components/SinglePicDialog.vue";
import {querySamplingImgById, querySamplingInfoList} from "~/api/projects_man.js";
import {formatDate} from "~/utils/timeUtils.js";
import CertificatePicDialog from "~/layout/components/CertificatePicDialog.vue";
import {querySampleSource} from "~/api/results_man.js";

// 统一管理loading状态
const loading = ref({
  table: false,    // 表格加载状态
  search: false,   // 搜索按钮加载状态
  reset: false,    // 重置按钮加载状态
});

// 搜索表单数据
const searchForm = ref({
  sampleDate: '',
  sampleNumber: '',
  sampleName: '',
  inspectionUnit: '',
  sampleStatus: ''
});

// 定义检测结果选项
const sampleStatusStrs = ref([
  {value: '0', label: '未检'},
  {value: '1', label: '已检'}
]);

// 表格数据
const tableData = ref([]);
// 当前页码
const currentPage = ref(1);
// 每页显示的条数
const pageSize = ref(10);
// 总记录数
const total = ref(0);

// 统计相关数据
const totalTasks = ref(0);           // 总采样数量
const testedTasks = ref(0);          // 已检测数量
const untestedTasks = ref(0);        // 未检测数量
const todayTasks = ref(0);           // 今日采样数量
const todayTestedTasks = ref(0);     // 今日已检数量
const todayUntestedTasks = ref(0);   // 今日未检数量

// 图片弹窗相关状态 - 分别管理两个弹窗
const singlePicDialog = ref({
  visible: false,
  title: '',
  imageData: null,
  loading: false
});

const certificatePicDialog = ref({
  visible: false,
  title: '',
  samplerImageData: null,
  inspectionImageData: null,
  loading: false
});

// 获取采样图片弹窗
const showSampling = async (row) => {
  try {
    const imgRes = await querySamplingImgById(row.imageUrl);

    if (imgRes.code === 10000) {
      singlePicDialog.value = {
        ...singlePicDialog.value,
        title: `采样图片 - ${row.sampleNumber}`,
        imageData: imgRes.data.imgBinary,
        loading: true,
        visible: true
      };
    } else {
      throw new Error('加载图片失败');
    }
  } catch (error) {
    console.error(' 加载图片失败:', error);
    ElMessage.error(' 加载图片失败');
    singlePicDialog.value.imageData = null;
  } finally {
    singlePicDialog.value.loading = false;
  }
};

// 显示签名图片弹窗
const showCertificatePicDialog = async (row) => {
  try {
    // 同时获取两张图片
    const [samplerRes, inspectionRes] = await Promise.all([
      querySamplingImgById(row.samplingSignatureId),
      querySamplingImgById(row.stallSignatureId)
    ]);

    if (samplerRes.code === 10000) {
      certificatePicDialog.value = {
        ...certificatePicDialog.value,
        title: `签名图片 - ${row.sampleNumber}`,
        samplerImageData: samplerRes.data.imgBinary,
        loading: true,
        visible: true
      };
    } else {
      throw new Error('采样人员图片加载失败');
    }

    if (inspectionRes.code === 10000) {
      certificatePicDialog.value.inspectionImageData = inspectionRes.data.imgBinary;
    } else {
      throw new Error('被检单位图片加载失败');
    }
  } catch (error) {
    console.error(' 加载图片失败:', error);
    ElMessage.error(error.message || '加载图片失败');
    certificatePicDialog.value.samplerImageData = null;
    certificatePicDialog.value.inspectionImageData = null;
  } finally {
    certificatePicDialog.value.loading = false;
  }
};

// 计算当前页的数据
const currentTableData = computed(() => {
  return tableData.value;
});

// 搜索操作
const search = async () => {
  try {
    loading.value.search = true;
    loading.value.table = true;
    currentPage.value = 1;
    await fetchTestResultsData();
    ElMessage.success(' 查询成功');
  } catch (error) {
    ElMessage.error(' 搜索失败');
  } finally {
    loading.value.search = false;
    loading.value.table = false;
  }
};

// 重置搜索
const resetSearch = async () => {
  try {
    loading.value.reset = true;
    searchForm.value = {
      sampleDate: '',
      sampleNumber: '',
      sampleName: '',
      inspectionUnit: '',
      sampleStatus: ''
    };
    await search();
  } finally {
    loading.value.reset = false;
  }
};

// 分页大小变化
const handleSizeChange = async (val) => {
  try {
    loading.value.table = true;
    pageSize.value = val;
    currentPage.value = 1;
    await fetchTestResultsData();
  } catch (error) {
    ElMessage.error(' 获取数据失败');
  } finally {
    loading.value.table = false;
  }
};

// 分页切换时触发
const handleCurrentChange = async (val) => {
  try {
    loading.value.table = true;
    currentPage.value = val;
    await fetchTestResultsData();
  } catch (error) {
    ElMessage.error(' 获取数据失败');
  } finally {
    loading.value.table = false;
  }
};

// 行点击事件
const handleRowClick = (row) => {
  console.log(' 点击行:', row);
};

// 定义被检单位选项
const inspectionUnitOptions = ref([]);

// 模拟从接口获取被检单位数据
const fetchInspectionUnits = async () => {
  try {
    const type = 1; // 被检单位
    const unitRes = await querySampleSource(type);

    if (unitRes.code === 10000){
      inspectionUnitOptions.value = unitRes.data.map(item => ({
        label: item.SourceName,
        value: item.SourceName
      }));
    } else {
      throw new Error(' 接口返回错误');
    }

  } catch (error) {
    console.error(error);
    ElMessage.error(' 获取被检单位失败');
  }
};

// 模拟从接口获取检测结果数据
const fetchTestResultsData = async () => {
  try {
    const params = {
      ...searchForm.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    const samplingRes = await querySamplingInfoList();

    if (samplingRes.code === 10000) {
      let filteredData = samplingRes.data.map(item => ({
        sampleDate: formatDate(item.InspectionDate.Time),
        sampleNumber: item.SampleCode.String,
        sampleStaff: item.SamplingUnit.String, // 检测单位
        sampleName: item.SampleName.String,
        sampleCategory: item.SampleCategory.String, // 样品大类
        inspectionUnit: item.InspectionUnit.String, // 被检单位
        sampleSource: item.SampleSource.String, // 样品来源
        locationInfo: item.LocationInfo.String, // 定位信息
        imageUrl: item.SampleImageId.String, // 采样图片
        samplingSignatureId: item.SamplingSignatureId.String, // 采样人员图片
        stallSignatureId: item.StallSignatureId.String, // 抽检单位图片
        sampleStatus: item.IsInspected ? '已检' : '未检' // 检测状态
      }));

      // 获取当前日期
      const today = new Date().toISOString().split('T')[0];

      // 计算总体统计数据
      totalTasks.value = filteredData.length;
      testedTasks.value = filteredData.filter(item => item.sampleStatus === '已检').length;
      untestedTasks.value = totalTasks.value - testedTasks.value;

      // 计算今日统计数据
      const todayData = filteredData.filter(item => item.sampleDate.includes(today));
      todayTasks.value = todayData.length;
      todayTestedTasks.value = todayData.filter(item => item.sampleStatus === '已检').length;
      todayUntestedTasks.value = todayTasks.value - todayTestedTasks.value;

      // 筛选逻辑保持不变
      if (params.sampleDate) {
        filteredData = filteredData.filter(item => item.sampleDate.startsWith(params.sampleDate));
      }
      if (params.sampleNumber) {
        filteredData = filteredData.filter(item =>
            item.sampleNumber.includes(params.sampleNumber)
        );
      }
      if (params.sampleName) {
        filteredData = filteredData.filter(item =>
            item.sampleName.includes(params.sampleName)
        );
      }
      if (params.sampleStatus) {
        const status = params.sampleStatus === '0' ? '未检' : '已检';
        filteredData = filteredData.filter(item => item.sampleStatus === status);
      }
      if (params.inspectionUnit) {
        filteredData = filteredData.filter(item =>
            item.inspectionUnit === params.inspectionUnit
        );
      }

      // 分页逻辑保持不变
      const start = (params.pageNum - 1) * params.pageSize;
      const end = start + params.pageSize;
      const pageData = filteredData.slice(start, end);

      tableData.value = pageData; // 更新表格数据
      total.value = filteredData.length;    // 更新总记录数
    } else {
      throw new Error('接口返回错误');
    }
  } catch (error) {
    console.error(' 获取采样数据失败:', error);
    ElMessage.error(' 获取采样数据失败');
  }
};

// 在组件挂载时调用接口获取数据
onMounted(async () => {
  loading.value.table = true;
  try {
    await Promise.all([
      fetchInspectionUnits(),
      fetchTestResultsData()
    ]);
  } catch (error) {
    ElMessage.error(' 初始化数据失败');
  } finally {
    loading.value.table = false;
  }
});
</script>

<style scoped>
.sample-info-query {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;
  gap: 16px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  border: 1px solid #f0f2f5;
}

.title-section {
  flex: 1;
  min-width: 0;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 24px;
  position: relative;
  padding-left: 12px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 16px;
  width: 4px;
  background: linear-gradient(to bottom, #437ae8, #5a9cf8);
  border-radius: 2px;
}

.search-section {
  width: 100%;
}

.form-item {
  margin-bottom: 18px;
}

.full-width {
  width: 100%;
}

.search-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
}

/* 统计信息区域 */
.stats-container {
  display: flex;
  gap: 16px;
}

.stats-section {
  flex: 1;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  border: 1px solid #f0f2f5;
  padding: 16px;
}

.stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 3px solid #437ae8;
}

.stats-cards {
  display: flex;
  gap: 16px;
}

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  border: 1px solid #f0f2f5;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  margin-right: 16px;
  color: #fff;
  font-size: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.total-icon {
  background: linear-gradient(135deg, #7b5ff5, #9b7df7);
}

.tested-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.untested-icon {
  background: linear-gradient(135deg, #e6a23c, #f0c14b);
}

.today-icon {
  background: linear-gradient(135deg, #409eff, #5a9cf8);
}

.today-tested-icon {
  background: linear-gradient(135deg, #11c78b, #2ed191);
}

.today-untested-icon {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-content {
  display: flex;
  font-weight: bold;
  flex-direction: column;
  min-width: 0;
}

.stat-label {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stat-value {
  font-size: 24px;
  color: #1d2129;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  flex: 1;
  padding: 8px 5px;
  white-space: nowrap;
}

.action-buttons .el-button .el-icon {
  margin-right: 4px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  overflow: hidden;
  border: 1px solid #f0f2f5;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

.pagination-wrapper {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f2f5;
  background-color: #fff;
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-border-color: #f0f2f5;
  --el-table-border: 1px solid #f0f2f5;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-row-hover-bg-color: #f7f9fc;
  width: 100% !important;
}

:deep(.el-table th) {
  background-color: #f7f8fa;
  color: #1d2129;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table td) {
  font-size: 14px;
  color: #4e5969;
}

:deep(.el-table__body tr.current-row  > td) {
  background-color: #f0f7ff;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped  td) {
  background-color: #fafbfc;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.2s;
}

:deep(.el-button--primary) {
  background: linear-gradient(to right, #437ae8, #5a9cf8);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(to right, #3a6bd4, #4e8ae6);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(67, 122, 232, 0.3);
}

:deep(.el-button:not(.el-button--primary)) {
  border: 1px solid #e5e6eb;
  background-color: #fff;
  color: #1d2129;
}

:deep(.el-button:not(.el-button--primary):hover) {
  border-color: #c9cdd4;
  background-color: #f7f8fa;
  color: #1d2129;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  padding: 0;
}

:deep(.el-pagination.is-background  .btn-next),
:deep(.el-pagination.is-background  .btn-prev),
:deep(.el-pagination.is-background  .el-pager li) {
  border-radius: 8px;
  background-color: #fff;
  border: 1px solid #e5e6eb;
  min-width: 32px;
  height: 32px;
  margin: 0 4px;
}

:deep(.el-pagination.is-background  .el-pager li:not(.is-disabled).is-active) {
  background: linear-gradient(to right, #437ae8, #5a9cf8);
  border-color: transparent;
  color: #fff;
}

/* 表单元素样式 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e5e6eb;
  transition: all 0.2s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c9cdd4;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #437ae8 !important;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .stats-cards {
    flex-wrap: wrap;
  }

  .stat-card {
    min-width: calc(50% - 8px);
  }
}

@media (max-width: 768px) {
  .header-container {
    flex-direction: column;
  }

  .stats-container {
    flex-direction: column;
  }

  .stat-card {
    min-width: 100%;
  }
}
</style>